<template >
  <basiccard :header_nav="header_nav">
    <el-alert show-icon title="警告提示的文案" type="warning"></el-alert>
    <el-row>
      <el-col>
        <span>选择商品分类:</span>
        <el-cascader
          :clearable="true"
          v-model="cateListIds"
          :options="cateList"
          expand-trigger="hover"
          :props="cateProps"
          :change-on-select="true"
          @change="cateChange"
        ></el-cascader>
      </el-col>
    </el-row>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="动态参数" name="many">
        <el-button type="success" :disabled="disTab" @click="addAttr">添加属性</el-button>
        <el-table :data="manyList" border>
          <el-table-column type="expand">
             <template slot-scope="scope">
             <div>
               <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)"
>{{item}}</el-tag>
<!-- 添加新的标签 -->

<el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
             </div>
           </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="editManyParams(scope.row.attr_id)">编辑</el-button>
              <el-button type="danger" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态参数" name="only">
        <el-button type="success" :disabled="disTab" @click="addParams">添加参数</el-button>
        <el-table :data="onlyList" border>
          <el-table-column type="expand">
           <template slot-scope="scope">
            
               <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable
>{{item}}</el-tag>
<!-- 添加新的标签 -->

<el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            
           </template>

          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="属性名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="editOnlyParams(scope.row.attr_id)" >编辑</el-button>
              <el-button type="danger" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!-- 添加属性or添加参数对话框 -->
    <el-dialog :title="getTitle" :visible.sync="addAttrVisible" width="50%"  @close="addDilogClose">
     <el-form ref="addformRef" :model="addform" label-width="100px" :rules="addformRules">
  <el-form-item :label="getTitle" prop="attr_name">
    <el-input v-model="addform.attr_name"></el-input>
  </el-form-item>
     </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAttrVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsFix">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑属性对话框 -->
       <el-dialog :title="'修改'+getTitle" :visible.sync="editAttrVisible" width="50%"  @close="editDilogClose">
     <el-form ref="editformRef" :model="editform" label-width="100px" :rules="editformRules">
  <el-form-item :label="getTitle" prop="attr_name">
    <el-input v-model="editform.attr_name"></el-input>
  </el-form-item>
     </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAttrVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsFix">确 定</el-button>
      </span>
    </el-dialog>
  </basiccard>
</template>
<script>
export default {
  name: "Params",
  data() {
    return {
      header_nav: {
        path: "/welecome",
        rolesMge: "商品管理",
        rolesList: "分类参数"
      },
      activeName: "many",
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 编辑属性框的显示
      editAttrVisible:false,
      title:'',
      addAttrVisible:false,
      cateListIds: [],
      cateList: [],
      manyList: [],
      onlyList: [],
      // 添加新标签的布尔值,废弃
      // inputVisible:false,
      // // 新标签绑定值
      // inputValue:'',
      // 编辑属性表单对象
      editform:{
        attr_name:'',
        attr_id:''
      },
      // 编辑表单验证规则对象
      editformRules:{
          attr_name:[
   { required: true, message: '请输入修改的属性名', trigger: 'blur' },
]
      },
      addform:{
       attr_name:'' 
      },
      addformRules:{
attr_name:[
   { required: true, message: '请输入添加的属性名', trigger: 'blur' },
]
  
      }
    };
  },
  methods: {
  //  添加新的标签触发方法
 async handleInputConfirm(val) {
    if(val.inputValue.trim().length==0){
      val.inputVisible = false
      return

    }
   val.attr_vals.push(val.inputValue.trim())
   val.inputValue = ''
   val.inputVisible = false
   const {data:res}   =  await this.$http.put(`categories/${this.getCateId}/attributes/${val.attr_id}`,{
        attr_name:val.attr_name,
        attr_sel:this.activeName,
         attr_vals :val.attr_vals.join(' ')
      })
      if(res.meta.status!==200) return this.$message.error('添加新的tag失败了')
      this.$message.success('添加成功')
   
  },
  // 展示标签输入方法
  showInput(val) {
    val.inputVisible = true
    // 页面元素直接渲染之后执行
     this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
  },

    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      this.cateList = res.data;
      console.log(this.cateList);
    },
    handleClick() {
      console.log(this.activeName);
      this.cateChange();
    },
    async cateChange() {
      if (this.cateListIds.length < 3) {
        this.cateListIds = [];
        return;
      }
      const { data: res } = await this.$http.get(
        `categories/${this.getCateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      );
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      res.data.forEach(element => {
      element.attr_vals = element.attr_vals?element.attr_vals.split(' '):[]
      element.inputVisible = false
      element.inputValue = ''
      });
      if (this.activeName === "many") {
        this.manyList = res.data;
 console.log(111);
 
        console.log(this.manyList);

        return;
      }
      this.onlyList = res.data;
      console.log(this.onlyList);
    },
    // 关闭对话框
    addDilogClose() {
       this.$refs.addformRef.resetFields()
    },
    // 开启编辑对话框
   async editOnlyParams(val) {
      
      this.editform.attr_id = val
     const {data:res} =  await this.$http.get(`categories/${this.getCateId}/attributes/${val}`,{
       params:{
         attr_sel:this.activeName
       }
     })
       if(res.meta.status!==200) return this.$message.error('获取信息失败')
       this.editform = res.data
       this.editAttrVisible = true
    } ,
    // 开启动态参数编辑对话框
   async editManyParams(val) {
       
      this.editform.attr_id = val
     const {data:res} =  await this.$http.get(`categories/${this.getCateId}/attributes/${val}`,{
       params:{
         attr_sel:this.activeName
       }
     })
       if(res.meta.status!==200) return this.$message.error('获取信息失败')
       this.editform = res.data
       this.editAttrVisible = true
   
    

    },
       // 关闭编辑属性对话框
    editDilogClose() {
      this.$refs.editformRef.resetFields()
    },
    addAttr() {
this.addAttrVisible = true
    },
    addParams() {
      this.addAttrVisible = true
    },
    addParamsFix() {
      this.$refs.addformRef.validate( async valid=>{
        if(!valid) return
       const {data:res}  =  await  this.$http.post(`categories/${this.cateListIds[2]}/attributes`,{
             attr_name:this.addform.attr_name,
             attr_sel:this.activeName,
           })
           if(res.meta.status!==201) return this.$message.error('添加失败')
               this.$message.success('添加成功')
           this.addAttrVisible = false
               this.cateChange()
      })
    },
    // 编辑表单的提交
    editParamsFix() {
        this.$refs.editformRef.validate( async valid=>{
          if(!valid) return
       const {data:res}  =  await this.$http.put(`categories/${this.getCateId}/attributes/${this.editform.attr_id}`,{
           attr_name:this.editform.attr_name,
            attr_sel:this.activeName
         })
         if(res.meta.status!==200) return this.$message.error('编辑失败')
         this.$message.success('编辑成功')
         this.cateChange()
         this.editAttrVisible = false
        })
    },
    // 删除属性
   async removeParams(val) {
        const confirmResult = await this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirmResult!=='confirm') return this.$message.info('取消了删除')
       const {data:res} = await  this.$http.delete(`categories/${this.getCateId}/attributes/${val}`)
       if(res.meta.status!==200) return this.$message.error('删除失败')
       this.$message.success('删除成功')
       this.cateChange()
    },
    // 删除tag
   async handleClose(i,val) {
      val.attr_vals.splice(i,1)
       const {data:res}   =  await this.$http.put(`categories/${this.getCateId}/attributes/${val.attr_id}`,{
        attr_name:val.attr_name,
        attr_sel:this.activeName,
         attr_vals :val.attr_vals.join(' ')
      })
      if(res.meta.status!==200) return this.$message.error('删除新的tag失败了')
      this.$message.success('删除成功')
    }
  },
  created() {
    this.getCateList();
  },
  computed: {
    disTab() {
      if (this.cateListIds.length !== 3) {
        return true;
      }
      return false;
    },
    getCateId() {
      if (this.cateListIds.length === 3) {
        return this.cateListIds[2];
      }
      return null;
    },
    getTitle() {
      if(this.activeName==='many'){
        return '动态参数'
      }
      return '静态参数'
    }
  }
};
</script>
<style lang="scss" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-row {
  padding-left: 2px;
  font-size: 14px;
}
.el-cascader {
  margin-left: 15px;
}
.el-tag {
  margin-left: 20px;
}
.input-new-tag {
  width: 120px;
}
</style>